<?php
namespace app\modules\v2\controllers;

use app\common\ApiResponse;
use yii\base\InvalidConfigException;
use yii\filters\auth\CompositeAuth;
use yii\filters\auth\HttpBearerAuth;
use yii\filters\auth\QueryParamAuth;
use yii\filters\Cors;
use yii\filters\RateLimiter;

/**
 * Api请求响应基类
 * 定义相关的认证方式、速率等
 */
class ApiBaseController extends \yii\rest\Controller
{
    public $modelClass;


    /**
     * @var ApiResponse
     */
    protected ApiResponse $_api;

    public function init()

    {

        parent::init();

        if ($this->modelClass === null) {

            throw new InvalidConfigException('The "modelClass" property must be set.');

        }

        $this->_api = new ApiResponse();
    }

    public function behaviors(): array
    {
        $behaviors = parent::behaviors();

        // 配置跨域
        $behaviors['corsFilter'] = [
            'class' => Cors::class,
            'cors' => [
                'Origin' => ['*'],
                'Access-Control-Request-Methods' => ['*'],
                'Access-Control-Request-Headers' => ['*'],
                'Access-Control-Allow-Credentials' => true,
            ]
        ];

        // 配置认证
        $behaviors['authenticator'] = [
            'class' => CompositeAuth::class,
            'authMethods' => [
                //配置API接口认证方式
                QueryParamAuth::class, // url中追加access-token=XXX
                HttpBearerAuth::class,  // Header 中追加Key：Authorization，Value：Bearer XXXX
            ],
        ];

        // 开启速率限制
        $behaviors['rateLimiter'] = [
            'class' => RateLimiter::class,
            'enableRateLimitHeaders' => true,
        ];

        //增加新的接口验证类，参数加密的sign
        $behaviors['tokenValidate'] = [
            //参数加密的sign所有接口都需要验证
            'class' => HttpSignAuth::class,
        ];

        $behaviors['authValidate'] = [
            'class' => HttpBasicAuth::class,
            //access-token 部分接口需要验证，需要排除比如 login register 这样的接口
            'optional' => ['register', 'login'],

        ];

        return $behaviors;
    }

    public function actions()
    {
        return [
            'index' => [
                'class' => 'yii\rest\IndexAction',
                'modelClass' => $this->modelClass,
                'checkAccess' => [$this, 'checkAccess'],
            ],
        ];
    }

    /**
     * {@inheritdoc}
     */
    protected function verbs()
    {
        return [
            'index' => ['GET', 'HEAD'],
        ];
    }

    public function checkAccess($action, $model = null, $params = [])
    {

    }


    public function actionIndex(): array
    {
        return $this->_api->success([
            'authMethods' => [
                'HttpBearerAuth',
                'QueryParamAuth',
            ]
        ]);
    }



}